package com.chinawayltd.ews.sample.service.algorithm.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.chinawayltd.ews.sample.mapper.TBranchMapper;
import com.chinawayltd.ews.sample.mapper.TLogMapper;
import com.chinawayltd.ews.sample.mapper.TVehicleCustomMapper;
import com.chinawayltd.ews.sample.mapper.TVehicleMapper;
import com.chinawayltd.ews.sample.mapper.algorithm.VehicleCustomExtendMapper;
import com.chinawayltd.ews.sample.model.TBranch;
import com.chinawayltd.ews.sample.model.TBranchExample;
import com.chinawayltd.ews.sample.model.TLog;
import com.chinawayltd.ews.sample.model.TVehicle;
import com.chinawayltd.ews.sample.model.TVehicleCustom;
import com.chinawayltd.ews.sample.model.TVehicleCustomExample;
import com.chinawayltd.ews.sample.model.TVehicleExample;
import com.chinawayltd.ews.sample.model.basicInfo.VehicleCustomVO;
import com.chinawayltd.ews.sample.service.algorithm.VehicleCustomService;
import com.chinawayltd.ews.sample.service.base.impl.BaseServiceImpl;
import com.chinawayltd.ews.sample.util.PageData;
import com.chinawayltd.ews.sample.util.excel.ExcelObjModel;
import com.chinawayltd.ews.sample.util.excel.ExportCloumsModel;
import com.chinawayltd.ews.sample.web.query.VehicleCustomGirdQuery;

/**
 * @program: greeProject
 * @description 
 * @author: chenxin
 * @create: 2018年5月2日 下午1:23:09
 */
@Service
public class VehicleCustomServiceImpl extends BaseServiceImpl implements VehicleCustomService{
	private static final SimpleDateFormat HHMM = new SimpleDateFormat("HH:mm");
	private static final SimpleDateFormat YYYYMMDD_HHMMSS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    TVehicleCustomMapper tVehicleCustomMapper;
    @Autowired
    VehicleCustomExtendMapper vehicleCustomExtendMapper;
    @Autowired
    private TLogMapper tLogMapper;
    @Autowired
    private TVehicleMapper tVehicleMapper;
    @Autowired
    private TBranchMapper tBranchMapper;
    private final String tableName = "T_VEHICLE_CUSTOM";
    
	@Override
	public List<VehicleCustomVO> listVehicleCustomByPage(VehicleCustomGirdQuery queryParam) {
		 return vehicleCustomExtendMapper.listVehicleCustomByPage(queryParam);
	}

	@Override
	@Transactional
	public int update(TVehicleCustom tVehicleCustom) {
		Date date = new Date();
		tVehicleCustom.setUpdateTime(date);
    	int result = tVehicleCustomMapper.updateByPrimaryKeySelective(tVehicleCustom);
        if(result > 0){
        	TLog log = new TLog();
    		log.setDataId(tVehicleCustom.getId());
    		log.setTableName(tableName);
    		log.setOperationUser(getCurrentUser().getRealname());
    		log.setOperationType(2);
    		log.setCreateTime(date);
    		log.setCreateTime(date);
    		tLogMapper.insertSelective(log);// 增加日记
		}
        return result;
	}

	@Override
	public TVehicleCustom getById(Long id) throws Exception{
		if(id == null || id <= 0){
            throw new RuntimeException("id不能为空或者少于等于0！");
        }
		return tVehicleCustomMapper.selectByPrimaryKey(id);
	}

	@Override
	public ExcelObjModel insertList(List<PageData> list){
		ExcelObjModel model = new ExcelObjModel();
		List<Object> mapList = new ArrayList<>();
		model.setCode(0); // 0没添加1添加成功，否则有添加不成功的

		// 遍历读取的Excel数据，判断数据的正确性
		errorContinue:
		for (PageData pd : list) {
			try {
				TVehicleCustom tVehicleCustom = new TVehicleCustom();
				Map<String, Object> resultMap = new HashMap<>();
				
				String carNum = pd.getString("var0");
				resultMap.put("carNum", carNum);
				String carVolume = pd.getString("var1");
				resultMap.put("carVolume", carVolume);
				if(StringUtils.isNoneBlank(carVolume)){
					tVehicleCustom.setCarVolume(Byte.valueOf(carVolume));
				}
				String beginWorkingTime = pd.getString("var2");
				if(StringUtils.isNoneBlank(beginWorkingTime)){
					beginWorkingTime = formatTimeToHHMM(beginWorkingTime);
					tVehicleCustom.setBeginWorkingTime(beginWorkingTime);
				}
				resultMap.put("beginWorkingTime", beginWorkingTime);
				
				String endWorkingTime = pd.getString("var3");
				if(StringUtils.isNoneBlank(endWorkingTime)){
					endWorkingTime = formatTimeToHHMM(endWorkingTime);
					tVehicleCustom.setEndWorkingTime(endWorkingTime);
				}
				resultMap.put("endWorkingTime", endWorkingTime);
				
				String workplaceBranchName = pd.getString("var4");
				resultMap.put("workplaceBranchName", workplaceBranchName);
				
				String dayShiftEarliestTime = pd.getString("var5");
				if(StringUtils.isNoneBlank(dayShiftEarliestTime)){
					dayShiftEarliestTime = formatTimeToHHMM(dayShiftEarliestTime);
					tVehicleCustom.setDayShiftEarliestTime(dayShiftEarliestTime);
				}
				resultMap.put("dayShiftEarliestTime", dayShiftEarliestTime);
				
				String dayShiftLatestTime = pd.getString("var6");
				if(StringUtils.isNoneBlank(dayShiftLatestTime)){
					dayShiftLatestTime = formatTimeToHHMM(dayShiftLatestTime);
					tVehicleCustom.setDayShiftLatestTime(dayShiftLatestTime);
				}
				resultMap.put("dayShiftLatestTime", dayShiftLatestTime);
				
				String nightShiftEarliestTime = pd.getString("var7");
				if(StringUtils.isNoneBlank(nightShiftEarliestTime)){
					nightShiftEarliestTime = formatTimeToHHMM(nightShiftEarliestTime);
					tVehicleCustom.setNightShiftEarliestTime(nightShiftEarliestTime);
				}
				resultMap.put("nightShiftEarliestTime", nightShiftEarliestTime);
				
				String nightShiftLatestTime = pd.getString("var8");
				if(StringUtils.isNoneBlank(nightShiftLatestTime)){
					nightShiftLatestTime = formatTimeToHHMM(nightShiftLatestTime);
					tVehicleCustom.setNightShiftLatestTime(nightShiftLatestTime);
				}
				resultMap.put("nightShiftLatestTime", nightShiftLatestTime);
				
				/*String carvldTime = pd.getString("var9");
				resultMap.put("carvldTime", carvldTime);
				if(StringUtils.isNoneBlank(carvldTime)){
					SimpleDateFormat sdf = carvldTime.length() < 17 ? YYYYMMDD_HHMM: YYYYMMDD_HHMMSS;
					tVehicleCustom.setCarvldTime(sdf.parse(carvldTime));
				}*/
				String carvldBranchName = pd.getString("var9");
				resultMap.put("carvldBranchName", carvldBranchName);
				
				for (int i = 0; i < 10; i++) {
					if (StringUtils.isBlank(pd.getString("var" + i))) {
						resultMap.put("describe", "填写的字段不能为空");
						mapList.add(resultMap);
						continue errorContinue;
					}
				}
				//比较时间
				Map<String, Object> compareTimeMap = this.compareTime(tVehicleCustom);
				if(!MapUtils.getBoolean(compareTimeMap, "flag")){
					resultMap.put("describe", MapUtils.getString(compareTimeMap, "describe"));
					mapList.add(resultMap);
				}
				//是否存在车牌号，存在更新，不存在新增
				Map<String, Object> judgeCarNumMap = this.judgeCarNum(carNum);
				if(MapUtils.getBoolean(judgeCarNumMap, "flag")){
					tVehicleCustom.setId(MapUtils.getLong(judgeCarNumMap, "id"));
				}else{
					resultMap.put("describe", "车牌号不存在");
					mapList.add(resultMap);
					continue errorContinue;
				}
				//判断站点是否存在
				Map<String, Object> branchMap1 = this.judgeBranchExist(workplaceBranchName);
				if(!MapUtils.getBoolean(branchMap1, "flag")){
					resultMap.put("describe", "车辆上下班站点"+MapUtils.getString(branchMap1, "describe"));
					mapList.add(resultMap);
					continue errorContinue;
				}else{
					tVehicleCustom.setWorkplaceBranch(MapUtils.getLong(branchMap1, "id"));
				}
				Map<String, Object> branchMap2 = this.judgeBranchExist(carvldBranchName);
				if(!MapUtils.getBoolean(branchMap2, "flag")){
					resultMap.put("describe", "车辆最早可用站点"+MapUtils.getString(branchMap2, "describe"));
					mapList.add(resultMap);
					continue errorContinue;
				}else{
					tVehicleCustom.setCarvldBranch(MapUtils.getLong(branchMap2, "id"));
				}
				Map<String, Object> leadData = this.toLeadData(tVehicleCustom);
				model.setCode(MapUtils.getInteger(leadData, "result"));
				if(MapUtils.getInteger(leadData, "result") > 0){
					resultMap.put("describe", MapUtils.getString(leadData, "describe"));
					mapList.add(resultMap);
				}else{
					resultMap.put("describe", "导入失败");
					mapList.add(resultMap);
					continue errorContinue;
				}
			} catch (Exception e) {
				e.printStackTrace();
				model.setCode(0);
				Map<String, Object> exceptionMap = new HashMap<>();
				exceptionMap.put("carNum", pd.getString("var0"));
				exceptionMap.put("carVolume", pd.getString("var1"));
				exceptionMap.put("beginWorkingTime", pd.getString("var2"));
				exceptionMap.put("endWorkingTime", pd.getString("var3"));
				exceptionMap.put("workplaceBranchName", pd.getString("var4"));
				exceptionMap.put("dayShiftEarliestTime", pd.getString("var5"));
				exceptionMap.put("dayShiftLatestTime", pd.getString("var6"));
				exceptionMap.put("nightShiftEarliestTime", pd.getString("var7"));
				exceptionMap.put("nightShiftLatestTime", pd.getString("var8"));
//				exceptionMap.put("carvldTime", pd.getString("var9"));
				exceptionMap.put("carvldBranchName", pd.getString("var9"));
				exceptionMap.put("describe", "数据异常，导入失败");
				mapList.add(exceptionMap);
			}
			
		}
		model.setList(mapList);
		List<ExportCloumsModel> cloums = new ArrayList<>();
		if (mapList.size() > 0) {
			cloums.add(new ExportCloumsModel("车牌号", "carNum"));
			cloums.add(new ExportCloumsModel("最大车位数", "carVolume"));
			cloums.add(new ExportCloumsModel("开始工作时间", "beginWorkingTime"));
			cloums.add(new ExportCloumsModel("结束工作时间", "endWorkingTime"));
			cloums.add(new ExportCloumsModel("车辆上下班站点", "workplaceBranchName"));
			cloums.add(new ExportCloumsModel("司机白班最早上下班时间", "dayShiftEarliestTime"));
			cloums.add(new ExportCloumsModel("司机白班最晚上下班时间", "dayShiftLatestTime"));
			cloums.add(new ExportCloumsModel("司机夜班最早上下班时间", "nightShiftEarliestTime"));
			cloums.add(new ExportCloumsModel("司机夜班最晚上下班时间", "nightShiftLatestTime"));
//			cloums.add(new ExportCloumsModel("车辆最早可用时间", "carvldTime"));
			cloums.add(new ExportCloumsModel("车辆最早可用站点", "carvldBranchName"));
			cloums.add(new ExportCloumsModel("导入描述", "describe"));
		}
		model.setCloums(cloums);
		return model;
	}
	
	private String formatTimeToHHMM( String time) throws ParseException {
		SimpleDateFormat sdf = time.length() < 6 ? HHMM : YYYYMMDD_HHMMSS;
		time = HHMM.format(sdf.parse(time));
		return time;
	}
	

	/**导入数据
	 * @author Fay
	 * @date 2018年5月14日 下午3:40:21
	 * @param tVehicleCustom
	 * @return
	 */
	@Transactional
	private Map<String, Object> toLeadData(TVehicleCustom tVehicleCustom) {
		int result = 0;
		Date date = new Date();
		Map<String, Object> resultMap = new HashMap<>();
		//查询自定义信息是否存在，存在则更新
		TVehicleCustomExample example = new TVehicleCustomExample();
		example.createCriteria().andIdEqualTo(tVehicleCustom.getId());
		List<TVehicleCustom> tvehicleComList = tVehicleCustomMapper.selectByExample(example);
		if(tvehicleComList.size() > 0){//存在 更新
			tVehicleCustom.setUpdateTime(date);
			result = tVehicleCustomMapper.updateByPrimaryKeySelective(tVehicleCustom);
			if(result > 0){
				TLog log = new TLog();
				log.setDataId(tVehicleCustom.getId());
				log.setTableName(tableName);
				log.setOperationUser(getCurrentUser().getRealname());
				log.setOperationType(2);
				log.setCreateTime(date);
				log.setUpdateTime(date);
				tLogMapper.insert(log);
			}
			resultMap.put("describe", "已更新");
		}else{//不存在 插入
			tVehicleCustom.setCreateTime(date);
			tVehicleCustom.setUpdateTime(date);
			result = tVehicleCustomMapper.insertSelective(tVehicleCustom);
			if(result > 0){
				TLog log = new TLog();
				log.setDataId(tVehicleCustom.getId());
				log.setTableName(tableName);
				log.setOperationUser(getCurrentUser().getRealname());
				log.setOperationType(1);
				log.setCreateTime(date);
				log.setUpdateTime(date);
				tLogMapper.insert(log);
			}
			resultMap.put("describe", "导入成功");
		}
		resultMap.put("result", result);
		return resultMap;
	}

	/**判断站点是否存在
	 * @author Fay
	 * @date 2018年5月14日 下午3:27:57
	 * @param branchName
	 * @return
	 */
	private Map<String, Object> judgeBranchExist(String branchName) {
		Map<String, Object> resultMap = new HashMap<>();
		
		TBranchExample example = new TBranchExample();
		example.createCriteria().andBranchNameEqualTo(branchName);
		List<TBranch> branchList1 = tBranchMapper.selectByExample(example);
		if(branchList1.size() > 0){//存在
			resultMap.put("flag", true);
			resultMap.put("id", branchList1.get(0).getId());
			return resultMap;
		}else{
			resultMap.put("describe", "不存在");
			resultMap.put("flag", false);
			return resultMap;
		}
	}

	/**比较时间前后是否冲突
	 * @author Fay
	 * @date 2018年5月14日 下午3:13:58
	 * @param tVehicleCustom
	 * @return
	 * @throws Exception 
	 */
	private Map<String, Object> compareTime(TVehicleCustom tVehicleCustom) throws Exception {
		Map<String, Object> resultMap = new HashMap<>();
		if(tVehicleCustom.getEndWorkingTime().equals("00:00") || tVehicleCustom.getEndWorkingTime().equals("0:00")){
			resultMap.put("describe", "结束工作时间不能为00:00");
			resultMap.put("flag", false);
			return resultMap;
		}
		if(tVehicleCustom.getDayShiftLatestTime().equals("00:00") || tVehicleCustom.getDayShiftLatestTime().equals("0:00")){
			resultMap.put("describe", "白班最晚上班时间不能为00:00");
			resultMap.put("flag", false);
			return resultMap;
		}
		if(tVehicleCustom.getNightShiftLatestTime().equals("00:00") || tVehicleCustom.getNightShiftLatestTime().equals("0:00")){
			resultMap.put("describe", "夜班最晚上班时间不能为00:00");
			resultMap.put("flag", false);
			return resultMap;
		}
		if(HHMM.parse(tVehicleCustom.getBeginWorkingTime()).getTime() > HHMM.parse(tVehicleCustom.getEndWorkingTime()).getTime()){
			resultMap.put("describe", "每天开始工作时间需要小于每天结束工作时间");
			resultMap.put("flag", false);
			return resultMap;
		}
		if(HHMM.parse(tVehicleCustom.getDayShiftEarliestTime()).getTime() > HHMM.parse(tVehicleCustom.getDayShiftLatestTime()).getTime()){
			resultMap.put("describe", "白班最早上班时间需要小于白班最晚上班时间");
			resultMap.put("flag", false);
			return resultMap;
		}
		if(HHMM.parse(tVehicleCustom.getNightShiftEarliestTime()).getTime() > HHMM.parse(tVehicleCustom.getNightShiftLatestTime()).getTime()){
			resultMap.put("describe", "夜班最早上班时间需要小于夜班最晚上班时间");
			resultMap.put("flag", false);
			return resultMap;
		}
		resultMap.put("flag", true);
		return resultMap;
	}

	/**是否存在车牌号，存在更新，不存在新增
	 * @author Fay
	 * @date 2018年5月14日 下午2:58:01
	 * @param tVehicleCustom
	 * @param carNum
	 * @return
	 */
	private Map<String, Object> judgeCarNum(String carNum) {
		Map<String, Object> resultMap = new HashMap<>();
		
		TVehicleExample example = new TVehicleExample();
		example.createCriteria().andCarNumEqualTo(carNum);
		List<TVehicle> vehicleList = tVehicleMapper.selectByExample(example);
		if(vehicleList.size() > 0){//证明存在,通常只有一条
			TVehicle tVehicle = vehicleList.get(0);
			resultMap.put("flag", true);
			resultMap.put("id", tVehicle.getId());
		}else{//不存在
			resultMap.put("flag", false);
		}
		return resultMap;
	}

	@Override
	public List<Map<String, Object>> exportGirdData(VehicleCustomGirdQuery queryParam) {
		return vehicleCustomExtendMapper.listVehicleCustomToMap(queryParam);
	}
	
}
